﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ETWJ.DTO;
using ETWJ.Iservice;
using ETWJ.Model;
using Microsoft.AspNetCore.Mvc;

namespace ETWJ.ERP.Controllers
{
    public class RolePermissionController : Controller
    {
        public IPermissionService<Permission,PermissionDTO> permissionService { get; set; }
        public IRoleService<Role,RoleDTO> roleService { get; set; }
        

        public RolePermissionController(IPermissionService<Permission, PermissionDTO> permissionService, IRoleService<Role, RoleDTO> roleService)
        {
            this.permissionService = permissionService;
            this.roleService = roleService;
        }


        #region 权限代码区


        public async Task<IActionResult> EditPermission(int id)
        {
            var model = await permissionService.GetByIdAsync(id);
            if (model == null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "不存在该用户！", isSuccess = "error" });

            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> EditPermission(PermissionDTO dto)
        {
            var model = await permissionService.GetByIdAsync(dto.Id);
            if (model == null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "不存在该权限！", isSuccess = "error" });

            }

            var result =await permissionService.Update(dto);


            if (result <= 0)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "修改失败！", isSuccess = "error" });

            }
            return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "修改成功！", isSuccess = "ok" });
        }

        public async Task<IActionResult> BatchPermissionDeleted(string ids)
        {
            string[] empIds = ids.Split(',');
            List<int> deletedResult = new List<int>();
            List<int> deletedResultIds = new List<int>();
            foreach (var id in empIds)
            {
                var data = await permissionService.GetByIdAsync(Convert.ToInt32(id));
                if (data != null)
                {
                    var result = await permissionService.MarkDeleted(data.Id);
                    deletedResult.Add(result);
                    deletedResultIds.Add(data.Id);
                }
            }

            if (deletedResult.Contains(-1))
            {
                string deletedFaillids = "";
                foreach (var id in deletedResultIds)
                {
                    deletedFaillids += id + "-";
                }
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "删除失败！删除失败的编号为：" + deletedFaillids, isSuccess = "OK" });
            }

            return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "删除成功！", isSuccess = "OK" });
        }

        public async Task<IActionResult> PermissionList(int pageIndex = 1, int count = 5)
        {
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }

            var model = await permissionService.GetByPage(pageIndex, count);
            var totalCount = await permissionService.GetTotalCountAsync();
            var currentPageIndex = pageIndex;

            var pageCount = Math.Ceiling(totalCount / 5.0);

            ViewBag.PageCount = pageCount;
            ViewBag.CurrentPageIndex = currentPageIndex;
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> AddPermission(Permission model)
        {

            var resp = await permissionService.GetPermissionByName(model.Name);
            if(resp!=null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "已存在该权限！", isSuccess = "error" });
            }

            var result=await permissionService.AddNewAsync(model);
            if(result<=0)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "添加失败！", isSuccess = "error" });

            }
            return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/PermissionList", msg = "添加成功！", isSuccess = "ok" });

        }

        public async Task<IActionResult> AddPermission()
        {
            return View();
        }


        #endregion


        #region 角色代码区

        public async Task<IActionResult> RoleDistrubution(int roleId)
        {
            var role = await roleService.GetByIdAsync(roleId);
            if(role==null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "不存在该角色！", isSuccess = "error" });
            }
            var rolePermission =await permissionService.GetPermissionByRoleIDAsync(roleId);

            var permissions =await permissionService.GetALL();


            RolePermissionEditModel model = new RolePermissionEditModel();
            model.Role = role;
            model.Permissions = permissions;
            model.RolePermissions = rolePermission;

            return View(model);
        }

        public async Task<IActionResult> RoleDistribution(RolePermissionPostEdit model)
        {
            if(model.PermissionId==null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "未给角色选择权限！", isSuccess = "error" });
            }

            var result = await permissionService.GetRoleDistrubutionPermAsync(model.RoleId, model.PermissionId);
            if(result<=0)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "分配权限失败！", isSuccess = "error" });
            }
            return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "分配权限成功！", isSuccess = "ok" });

        }

        public async Task<IActionResult> EditRole(int id)
        {
            var model = await roleService.GetByIdAsync(id);
            if (model == null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "不存在该角色！", isSuccess = "error" });

            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> EditRole(RoleDTO dto)
        {
            var model = await roleService.GetByIdAsync(dto.Id);
            if (model == null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "不存在该权限！", isSuccess = "error" });

            }

            var result = await roleService.Update(dto);


            if (result <= 0)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "修改失败！", isSuccess = "error" });

            }
            return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "修改成功！", isSuccess = "ok" });
        }

        public async Task<IActionResult> BatchRoleDeleted(string ids)
        {
            string[] empIds = ids.Split(',');
            List<int> deletedResult = new List<int>();
            List<int> deletedResultIds = new List<int>();
            foreach (var id in empIds)
            {
                var data = await roleService.GetByIdAsync(Convert.ToInt32(id));
                if (data != null)
                {
                    var result = await roleService.MarkDeleted(data.Id);
                    deletedResult.Add(result);
                    deletedResultIds.Add(data.Id);
                }
            }

            if (deletedResult.Contains(-1))
            {
                string deletedFaillids = "";
                foreach (var id in deletedResultIds)
                {
                    deletedFaillids += id + "-";
                }
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "删除失败！删除失败的编号为：" + deletedFaillids, isSuccess = "OK" });
            }

            return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "删除成功！", isSuccess = "OK" });
        }

        public async Task<IActionResult> RoleList(int pageIndex = 1, int count = 5)
        {
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }


            var model = await roleService.GetByPage(pageIndex, count);

            var totalCount = await roleService.GetTotalCountAsync();
            var currentPageIndex = pageIndex;

            var pageCount = Math.Ceiling(totalCount / 5.0);

            ViewBag.PageCount = pageCount;
            ViewBag.CurrentPageIndex = currentPageIndex;

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> AddRole(Role model)
        {

            var resp = await roleService.GetRoleByName(model.Name);
            if (resp != null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "已存在该角色！", isSuccess = "error" });
            }

            var result = await roleService.AddNewAsync(model);
            if (result <= 0)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "添加失败！", isSuccess = "error" });

            }
            return RedirectToAction("Tip", "Home", new { redirectUrl = "/RolePermission/RoleList", msg = "添加成功！", isSuccess = "ok" });

        }

        public async Task<IActionResult> AddRole()
        {
            return View();
        }


        #endregion

    }
}